<template>
  <div class="page-container fullpage">
    <el-card>
      <h3>删除用户</h3>
      <div style="margin-top:12px">是否确认删除用户 <strong>{{ username }}</strong>？此操作不可恢复。</div>
      <div style="margin-top:12px; text-align:right">
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        <el-button style="margin-left:8px" @click="() => router.push('/admin/users')">返回用户管理</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import api from '../utils/api'

const route = useRoute()
const router = useRouter()
const username = route.params.username as string || ''

const tryDeleteFallbacks = async (username: string) => {
  const attempts = [
    async () => await api.delete('/user', { params: { username } }),
    async () => await api.delete(`/user/${encodeURIComponent(username)}`),
    async () => await api.post('/user/delete', { username }),
    async () => await api.post('/users/delete', { username })
  ]
  let lastErr: any = null
  for (const fn of attempts) {
    try {
      const r: any = await fn()
      if (!r) continue
      if (r.operationResult === 'SUCC' || r?.success === true) return { ok: true, resp: r }
      return { ok: true, resp: r }
    } catch (e) {
      lastErr = e
      console.warn('delete attempt failed', e)
    }
  }
  return { ok: false, err: lastErr }
}

const confirmDelete = async () => {
  if (!username) return
  try {
    const result = await tryDeleteFallbacks(username)
    if (result.ok) {
      try { router.push('/admin/users') } catch (e) {}
    } else { console.error('all delete attempts failed', result.err) }
  } catch (err) { console.error('delete', err) }
}
</script>

<style scoped>
.page-container { padding: 16px }
</style>
